<template>
  <div style="height: 100%;">
    <router-view v-slot="{ Component, route: matchedRoute }">
      <keep-alive :include="cachedRoutes">
        <component
          :is="Component"
          :key="generateComponentKey(matchedRoute)"
        />
      </keep-alive>
    </router-view>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, getCurrentInstance, nextTick } from 'vue'
import { useRoute,useRouter } from 'vue-router';
const route = useRoute();
const cachedRoutes = ref<any[]>([]);
const refreshCounters = ref<Record<string, number>>({});

function generateComponentKey(matchedRoute: any) {
  const currentPath = matchedRoute.path;
  const refreshCount = refreshCounters.value[currentPath] || 0;
  return `${currentPath}?count=${refreshCount}`;
}

const refreshPage = async (pathToRefresh?: string) => {
  const targetPath = pathToRefresh || route.fullPath;
  refreshCounters.value[targetPath] = (refreshCounters.value[targetPath] || 0) + 1;
};

onMounted(() => {
  window.addEventListener('mainRefresh', handleMainRefresh)
});
function handleMainRefresh(event:any) {
  if (event.detail && event.detail.path  && event.detail.appKey == 'sub2-app') {
    refreshPage(event.detail.path)
  }
}
watch(route, (newVal) => {
  let name = newVal.matched.map(r => r.components?.default?.name).filter(Boolean)
  if (name[0] && cachedRoutes.value.indexOf(name[0]) == -1) {
    // 如果是已经刷新进来的，就不要再添加到缓存中
    cachedRoutes.value.push(name[0])
  }
}, { immediate: true })
</script>


<style scoped>
</style>